<?php

namespace api\modules\backend\models;

use Yii;
use \yii\db\ActiveRecord;

/**
 * District Model
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class District extends ActiveRecord
{
    private $parent_id;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%district}}';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['district_id'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['district_name'], 'required'],
            [['district_name'], 'unique'],
            [['parent_id'], 'integer'],
            [['parent_id'], 'checkParent']
        ];
    }

    public function checkParent($attribute)
    {
        if ($this->parent_id) {
            $parent = self::findOne(['district_id' => $this->parent_id]);

            if (empty($parent)) {
                $this->addError($attribute, "的值不可以为空.");
            }
        }
    }

    static function removeChild($parent_id)
    {
        $result = self::find()->where(['parent_id' => $parent_id])->count();

        if (empty($result)) return true;

        return self::updateAllCounters(['is_deleted' => 1], ['parent_id' => $parent_id]);
    }
}
